#include "Stdafx.h"

#include "EndGameDb.h"

namespace EndGameDB
{

	// progress function
	void (*OnCompressSubDbStartedPtr)(int wm, int wk, int bm, int bk, int wmrank, int bmrank);

	// compressed file headers
	EGTBMainHeader mainHeaderWDL;
	EGTBMainHeader mainHeaderDTM;

	EGTBSubDatabase* pWDLSubDbs;
	EGTBSubDatabase* pDTMSubDbs;

	uint64 nWDLTotalBlockCount;
	uint64 nDTMTotalBlockCount;


	// compression settings
	int32 g_nCompressionType;
	eCheckersType g_eCompressionCheckersType;
	uint32 g_nPageSize;
	uint32 g_nSubDbCount;
	uint32 g_nSubDbIndex;


	// paging managers - provides compression stream
	PagingManager* g_pWDLPageManager;
	PagingManager* g_pDTMPageManager;


	// pointer to the databases which are currently being computed.
	uint8 *currentdb_b, *currentdb_w; 
	uint8	*cur_dtm_b, *cur_dtm_w;

	// output compression directory
	wchar_t szCprDatabaseDir[PATH_MAX];

	
	 // Initializes Compression
	////////////////////////////////////////////

	void InitCompress()
	{
		pWDLSubDbs = NULL;
		pDTMSubDbs = NULL;
		g_pWDLPageManager = NULL;
		g_pDTMPageManager = NULL;
	}


	 // Sets the compression directory
	////////////////////////////////////////////

	void SetDatabaseCprDirectory(const wchar_t* lpDir)
	{
		wcscpy_s(szCprDatabaseDir, PATH_MAX, lpDir);
	}


	 // Add compression directory to the file
	////////////////////////////////////////////

	void AttachCprDirectory(wchar_t* path, wchar_t *filename)
	{
		wcscpy_s(path, PATH_MAX, szCprDatabaseDir);
		int len = (int)wcslen(path);
		if(path[len - 1] != L'\\')
		{
			wcscat_s(path, PATH_MAX, L"\\");
		}

		wcscat_s(path, PATH_MAX, filename);
	}

	 // Finalizes the compression of one EGTB file
	////////////////////////////////////////////////////////

	void DoneDbCompression(FILE* wdlFile, FILE* dtmFile)
	{
		// seek to the beginning of files
		_fseeki64(wdlFile, 0, SEEK_SET);
		_fseeki64(dtmFile, 0, SEEK_SET);

		// write the main header
		fwrite(&mainHeaderWDL, sizeof(EGTBMainHeader), (size_t)1, wdlFile);
		fwrite(&mainHeaderDTM, sizeof(EGTBMainHeader), (size_t)1, dtmFile);

		// write subdb headers
		fwrite(pWDLSubDbs, sizeof(EGTBSubDatabase) * g_nSubDbCount, (size_t)1, wdlFile);
		fwrite(pDTMSubDbs, sizeof(EGTBSubDatabase) * g_nSubDbCount, (size_t)1, dtmFile);

		// free space
		delete[] pWDLSubDbs;
		delete[] pDTMSubDbs;

		// free page managers
		delete g_pWDLPageManager;
		delete g_pDTMPageManager;
	}
}
